package ru.aslanov.schedule.model;

import ru.aslanov.schedule.server.PMF;
import ru.aslanov.schedule.utils.MemCacheUtil;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import java.io.Serializable;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 8, 2010 6:26:25 PM
 *
 * @author Sergey Aslanov
 */
@PersistenceCapable
@EmbeddedOnly
public class UnownReference<T extends Entity> implements Serializable {
    private static final Logger log = Logger.getLogger(UnownReference.class.getName());

    @Persistent
    private String encodedKey;
    @NotPersistent
    private T object;
    @NotPersistent
    private Class<T> tClass;

    public UnownReference(Class<T> tClass) {
        this.tClass = tClass;
    }

    public String getEncodedKey() {
        if (encodedKey != null) {
            return encodedKey;
        } else if (object != null) {
            return object.getEncodedKey();
        } else {
            return null;
        }
    }

    public T getObject() {
        if (object != null) {
            return object;
        } else if (encodedKey != null) {
            return getObject(PMF.getThreadLocalPersistenceManager());
        } else {
            return null;
        }
    }

    public T getObject(PersistenceManager pm) {
        if (encodedKey != null) {
            return (T) MemCacheUtil.getAndCacheEntity(tClass, encodedKey);
            //return pm.getObjectById(tClass, encodedKey);
        } else {
            return object;
        }
    }

    public void setEncodedKey(String encodedKey) {
        this.encodedKey = encodedKey;
        this.object = null;
    }

    public void setObject(T object) {
        this.object = object;
        encodedKey = null;
    }
}
